"""
thread_local适用于同步请求的环境，这里先写着。我们主要的请求场景大部分是异步的
"""
import asyncio
import threading

from asgiref.sync import sync_to_async
from django.contrib.auth import get_user_model
from rest_framework_simplejwt.tokens import AccessToken

from HomeAutoAI.common.utils.Utils import async_get_user_from_token
from users.models import Users

User = get_user_model()  # 获取用户模型
thread_local = threading.local()


def get_user_from_token(token):
    try:
        access_token = AccessToken(token)
        print(f"Access Token: {access_token.payload}")
        user_id = access_token['user_id']
        return User.objects.get(user_id=user_id)
    except Exception as e:
        print(f"Token error: {e}")
        return None


def set_cur_token(token):
    """
    设置当前线程的token
    :param token:
    :return:
    """
    thread_local.token = token


def get_cur_token():
    """
    获取当前线程的token
    :return:
    """
    return getattr(thread_local, 'token', None)


def get_cur_user() -> Users:
    """
    获取当前线程的用户,如果没有返回None
    :return:
    """
    return get_user_from_token(get_cur_token())

